package com.quanyan.club.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.ReqClubAnnouncement;
import com.quanyan.club.entity.vo.req.ReqClubAnnouncementPage;
import com.quanyan.club.entity.vo.resp.RespClubAnnouncement;
import com.quanyan.club.mapper.TbClubAnnouncementMapper;
import com.quanyan.club.mapper.TbClubAnnouncementUidRelationMapper;
import com.quanyan.club.mapper.TbClubMemberMapper;
import com.quanyan.club.service.ClubAnnouncementService;
import com.quanyan.club.service.ClubMemberService;
import com.quanyan.club.service.CppService;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 俱乐部公告处理
 * Created by zhang on 16/5/30.
 */
@Service("clubAnnouncementService")
public class ClubAnnouncementServiceImpl extends BaseServiceImpl implements ClubAnnouncementService {


    @Autowired
    private TbClubAnnouncementMapper clubAnnouncementMapper;

    @Autowired
    private TbClubAnnouncementUidRelationMapper clubAnnouncementUidRelationMapper;

    @Autowired
    private UserServiceFacade userServiceFacade;

    @Autowired
    private CppService cppService;
    @Autowired
    private ClubMemberService clubMemberService;

    @Value("${message.push.service.url}")
    public String messagePushServiceUrl;

    @Autowired
    private TbClubMemberMapper clubMemberMapper;

    /**
     * 获取俱乐部公告列表
     * @param reqClubAnnouncementPage
     * @return
     */
    @Override
    public PageObj selectClubAnnouncementList(ReqClubAnnouncementPage reqClubAnnouncementPage,int uid) {
        int clubId = (Integer) reqClubAnnouncementPage.getParamMap().get("clubId");

        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId).andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(example);

        String roleCode = "";
        if (clubMembers != null && clubMembers.size() != 0){
            roleCode = clubMembers.get(0).getRoleCode();
        }else {
            throw new BizException("非俱乐部成员，不能查看公告！");
        }

        TbClubAnnouncementExample clubAnnouncementExample = new TbClubAnnouncementExample();
        TbClubAnnouncementExample.Criteria criteria = clubAnnouncementExample.createCriteria();
        criteria.andClubIdEqualTo(clubId);
        //查询状态为未删除的公告:0为未删除，1为已删除
        criteria.andIsDeleteEqualTo(0);

        int total = clubAnnouncementMapper.countByExample(clubAnnouncementExample);

        int pageNum = reqClubAnnouncementPage.getPageNum();

        int pageSize = reqClubAnnouncementPage.getPageSize();

        clubAnnouncementExample.setOrderByClause(" publish_date desc");
        clubAnnouncementExample.setPage(Page.createPage(total,pageNum,pageSize));

        List<TbClubAnnouncement> clubAnnouncementList = clubAnnouncementMapper.selectByExample(clubAnnouncementExample);

        List<RespClubAnnouncement> records = new ArrayList<>();

        List<Integer> isNotReadList = new ArrayList<>();
        if (clubAnnouncementList.isEmpty()) {

        } else {
            RespClubAnnouncement respClubAnnouncement;
            for (TbClubAnnouncement tbClubAnnouncement : clubAnnouncementList) {
                respClubAnnouncement = new RespClubAnnouncement();
                respClubAnnouncement.setClubId(tbClubAnnouncement.getClubId());
                respClubAnnouncement.setContent(tbClubAnnouncement.getContent());
                respClubAnnouncement.setId(tbClubAnnouncement.getId());
                respClubAnnouncement.setPublishDate(tbClubAnnouncement.getPublishDate().getTime());
                respClubAnnouncement.setPublishName(tbClubAnnouncement.getPublishName());
                respClubAnnouncement.setPublishUid(tbClubAnnouncement.getPublishUid());
                respClubAnnouncement.setTitle(tbClubAnnouncement.getTitle());
                respClubAnnouncement.setRoleCode(roleCode);
                if(this.announcementIsRead(uid,tbClubAnnouncement.getId())){
                    respClubAnnouncement.setIsRead(1);  //公告已读
                }else{
                    respClubAnnouncement.setIsRead(0);  //公告未读
                    isNotReadList.add(tbClubAnnouncement.getId());
                }
                records.add(respClubAnnouncement);
            }
        }
        //将未读公告设置为已读
        if(!isNotReadList.isEmpty()){
            clubAnnouncementUpdate(isNotReadList,clubId,uid);
        }
        PageObj pageObj = PageObj.create(total,pageNum,pageSize,records);
        return pageObj;
    }

    /**
     * 添加俱乐部公告信息
     * @param reqClubAnnouncement
     * @return
     */
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int addClubAnnouncement(ReqClubAnnouncement reqClubAnnouncement,int uid) {

        if (!clubMemberService.isClubAdminMember(uid, reqClubAnnouncement.getClubId())){
            throw new BizException("无权限发布公告！");
        }

        APIResponse<RespUserInfoBase> response = this.userServiceFacade.queryUserInfo(uid);
        if(response.isRet()){
            RespUserInfoBase user = response.getData();
            String nickName = "";
            if(user != null && user.getNickName()!= null){
                nickName = user.getNickName();
            }
            String title = reqClubAnnouncement.getTitle();
            String content = reqClubAnnouncement.getContent();
            int clubId = reqClubAnnouncement.getClubId();
            int n = this.insertClubAnnouncement(clubId,
                    title,
                    content,
                    uid,
                    nickName);
            TbClub club = super.getClub(clubId);
            //进行消息推送，通知俱乐部成员
            cppService.pushClubAnnouncement(clubId,content,title,club);
            return n;
        } else {
            return 0;
        }
    }

    /**
     * 删除俱乐部公告信息
     * @param announcementId
     * @return
     */
    @Override
    public int deleteClubAnnouncement(int announcementId,int uid) {

        //获取要删除的公告信息详情
        TbClubAnnouncement clubAnnouncement = this.clubAnnouncementMapper.selectByPrimaryKey(announcementId);
        if (clubAnnouncement != null) {
            TbClubMember member = super.getClubMember(uid,clubAnnouncement.getClubId());
            if (member != null) {
                if (member.getRoleCode().equals(Constants.ClubRole.ROLE_CLUB_MEMBER)) {
                    return -1;
                } else {
                    clubAnnouncement.setIsDelete(1);
                    int n = this.clubAnnouncementMapper.updateByPrimaryKey(clubAnnouncement);
                    return n;
                }


            } else {
                return -1;
            }
        }else{
            return -2;
        }
    }
    /**
     * 判断俱乐部公告是否已读
     * @param uid
     * @param announcementId
     * @return true为已读，false为未读
     */
    private boolean announcementIsRead(int uid,int announcementId){
        TbClubAnnouncementUidRelationExample example = new TbClubAnnouncementUidRelationExample();
        TbClubAnnouncementUidRelationExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andAnnouncementIdEqualTo(announcementId);
        //标志公告是否删除：0为未删除，1为已删除
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        int total = clubAnnouncementUidRelationMapper.countByExample(example);
        return total > 0;
    }

    /**
     * 添加俱乐部公告信息
     * @param clubId    俱乐部ID
     * @param title     公告标题
     * @param content   公告正文
     * @param publishUid    公告发布人ID
     * @param publishName   公告发布人姓名
     * @return
     */
    private int insertClubAnnouncement(int clubId,String title,String content,int publishUid,String publishName){
        TbClubAnnouncement clubAnnouncement = new TbClubAnnouncement();
        clubAnnouncement.setPublishName(publishName);
        clubAnnouncement.setPublishUid(publishUid);
        clubAnnouncement.setPublishDate(new Date());
        clubAnnouncement.setContent(content);
        clubAnnouncement.setClubId(clubId);
        clubAnnouncement.setTitle(title);
        int n = clubAnnouncementMapper.insertSelective(clubAnnouncement);
        return n;
    }

    /**
     * 更新俱乐部通告已读状态
     * @param isNotReadList
     * @param clubId
     * @param uid
     * @return
     */
    private int clubAnnouncementUpdate(List<Integer> isNotReadList,Integer clubId, Integer uid){
            TbClubAnnouncementUidRelation clubAnnouncementUidRelation;
            for (Integer announcementId : isNotReadList) {
                clubAnnouncementUidRelation = new TbClubAnnouncementUidRelation();
                clubAnnouncementUidRelation.setAnnouncementId(announcementId);
                clubAnnouncementUidRelation.setClubId(clubId);
                clubAnnouncementUidRelation.setUid(uid);
                int n = insertClubAnnouncementUidRelation(clubAnnouncementUidRelation);
                if(n == 0){
                    insertClubAnnouncementUidRelation(clubAnnouncementUidRelation);
                }
            }
        return 1;
    }

    /**
     * 插入用户与俱乐部公告关系
     * @param clubAnnouncementUidRelation
     * @return
     */
    private int insertClubAnnouncementUidRelation(TbClubAnnouncementUidRelation clubAnnouncementUidRelation){
        int n = clubAnnouncementUidRelationMapper.insertSelective(clubAnnouncementUidRelation);
        return  n;
    }


}
